import os
import time

from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By

from ocr import ocrImage


def getCode():
    # 截取屏幕内容，保存到本地
    driver.save_screenshot("img/01.png")
    # 打开截图，获取验证码位置，截取保存验证码
    ran = Image.open("img/01.png")
    box = (328, 253, 427, 282)  # 左，上，右，下
    return ocrImage(ran.crop(box))  # 读取验证码


def create_str_to_txt(str_data):
    path_file_name = 'result.txt'
    if not os.path.exists(path_file_name):
        with open(path_file_name, "w") as f:
            print(f)

    with open(path_file_name, "a") as f:
        f.write('%s\n' % str_data)


url = "https://"

# 打开浏览器，最大化浏览器
driver = webdriver.Chrome("chromedriver.exe")
driver.get(url)
driver.implicitly_wait(5)
driver.maximize_window()
driver.execute_script("document.getElementById('checkCode1').style.width='100px'")

# 用户名元素
userElement = driver.find_element(By.XPATH, "//input[@id='vehicle-no']")
# 验证码输入框元素
codeElement = driver.find_element(By.XPATH, "//input[@id='codeText1']")
# 验证图片元素
imgElement = driver.find_element(By.XPATH, "//img[@id='checkCode1']")
# 提交元素
click_login = driver.find_element(By.XPATH, "//div[@id='submit-btn1']")
# 结果元素
resultElement = driver.find_element(By.XPATH, "//div[@id='result1']")

array = []
end = len(array)
point = 0

while point != end:
    code = getCode()
    if len(code) != 4:
        code = '1111'

    # 收到验证码，进行输入验证
    userElement.clear()
    codeElement.clear()
    userElement.send_keys(array[point])
    codeElement.send_keys(code)
    click_login.click()
    time.sleep(0.25)

    if resultElement.text == '验证码错误，请重新输入！' or resultElement.text == '正在查询':
        codeElement.click()
        time.sleep(0.25)
    else:
        data = array[point] + ": " + "".join(resultElement.text.split())
        create_str_to_txt(data)
        print(data)
        point += 1
